﻿using System.Data;
using BLL.DTO.UserDto;
using BLL.Manager;
using Helper;
using HZY.Framework.DependencyInjection;
using Model.EntityInfo;
using Sunny.UI;
using WinFormsSprayProcessSCADASystem.Extension;

namespace WinFormsSprayProcessSCADASystem
{
    public partial class PageUserManage : UIPage, IScopedSelfDependency 
    {
        private readonly UserManager _userManager;
        private readonly RoleManager _roleManager;
        public PageUserManage(UserManager userManager, RoleManager roleManager)
        {
            InitializeComponent();
            this._userManager = userManager;
            this._roleManager = roleManager;
            this.Load += PageUserManage_Load;
        }

        private void PageUserManage_Load(object? sender, EventArgs e)
        {
            LoadData();
        }

        private async void LoadData()
        {
            await Task.WhenAll(GetAllUser(), GetAllRole());
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_AddUser_Click(object sender, EventArgs e)
        {
            if (txt_UserName.Text.Length == 0)
            {
                this.ShowWarning("用户名不能为空");
                return;
            }
            if (txt_Password.Text != txt_EnterPassword.Text)
            {
                this.ShowWarning("两次密码输入不一致");
                return;
            }
            if (cb_Auth.SelectedItem == null)
            {

                this.ShowWarning("请选择用户角色");
                return;
            }
            var res = await this._userManager.CreateUserAsync(new UserCreateDto
            {
                UserName = txt_UserName.Text,
                UserPassword = txt_Password.Text,
                RoleId = (cb_Auth.SelectedItem as RoleInfoModel).Id,
            });
            if (res.Code == SystemEnums.ResCode.Success)
            {
                await this.GetAllUser();
            }
            else
            {
                this.ShowError(res.Msg);
            }
        }
        /// <summary>
        /// 获取所有的用户账号
        /// </summary>
        /// <returns></returns>
        private async Task<int> GetAllUser()
        {
            var res = await _userManager.GetUserLidtAsync();
            if (res.Code == Helper.SystemEnums.ResCode.Success)
            {

                var _list = res.Data as List<UserInfoModel>;
                dgv_User.DataSource = _list.Select(x => new
                {
                    Id = x.Id,
                    UserName = x.UserName,
                    UserPassword = x.UserPassword,
                    Role = x.RoleInfo.Name,
                    RoleId = x.RoleInfo.Id,
                }).ToList();
                dgv_User.Refresh();
                return 1;
            }
            return 0;
        }
        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <returns></returns>
        private async Task<int> GetAllRole()
        {
            var res = await _roleManager.GetAllRole();
            if (res.Code == Helper.SystemEnums.ResCode.Success)
            {

                var _list = res.Data as List<RoleInfoModel>;
                foreach (RoleInfoModel row in _list)
                {
                    this.cb_Auth.Items.Add(row);
                }
                this.BackShowSelectInput();
                return 1;
            }
            return 0;
        }

        private void dgv_User_DataSourceChanged(object sender, EventArgs e)
        {
            if (dgv_User.SelectedRows.Count > 0)
            {
                // 获取选中的第一行（单选模式下只有一行）
                DataGridViewRow selectedRow = dgv_User.SelectedRows[0];

                // 获取单元格数据（示例：获取第一列的值）
                string cellValue = selectedRow.Cells[0].Value.ToString();


                txt_UserName.Text = selectedRow.Cells[1].Value.ToString();
                txt_Password.Text = selectedRow.Cells[2].Value.ToString();
                txt_EnterPassword.Text = selectedRow.Cells[2].Value.ToString();
                var Id = Convert.ToInt32(selectedRow.Cells[4].Value);


                this.BackShowSelectInput();
            }
        }
        /// <summary>
        /// 回显下拉选择框
        /// </summary>
        private void BackShowSelectInput()
        {
            if (dgv_User.SelectedRows.Count > 0 && cb_Auth.Items.Count > 0)
            {
                DataGridViewRow selectedRow = dgv_User.SelectedRows[0];
                var Id = Convert.ToInt32(selectedRow.Cells[4].Value);
                foreach (RoleInfoModel item in cb_Auth.Items)
                {
                    if (Convert.ToInt32(item.Id) == Id)
                    {
                        cb_Auth.SelectedItem = item;
                        return;
                    }
                }
            }
        }

        private void dgv_User_SelectionChanged(object sender, EventArgs e)
        {
            this.dgv_User_DataSourceChanged(sender, e);
        }
        /// <summary>
        /// 删除选中的用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_Delete_Click(object sender, EventArgs e)
        {
            if (this.ShowAskDialog2("您确定要删除选中的用户吗？", true))
            {
                if (dgv_User.SelectedRows.Count > 0)
                {
                    // 获取选中的第一行（单选模式下只有一行）
                    DataGridViewRow selectedRow = dgv_User.SelectedRows[0];

                    var res = await this._userManager.DelUserAsync(new UserDeleteDto()
                    {
                        Id = Convert.ToInt32(selectedRow.Cells[0].Value)
                    });

                    if (res.Code == SystemEnums.ResCode.Success)
                    {
                        this.ShowOk("更新成功！");
                        this.GetAllUser();
                    }
                    else
                    {
                        this.ShowError(res.Msg);
                    }


                }
            };
        }
        /// <summary>
        /// 修改选中的用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_Update_Click(object sender, EventArgs e)
        {
            if (this.ShowAskDialog2("您确定要更新选中的用户吗？", true))
            {
                if (dgv_User.SelectedRows.Count > 0)
                {
                    // 获取选中的第一行（单选模式下只有一行）
                    DataGridViewRow selectedRow = dgv_User.SelectedRows[0];

                    if (txt_UserName.Text.Length == 0)
                    {
                        this.ShowWarning("用户名不能为空");
                        return;
                    }
                    if (txt_Password.Text != txt_EnterPassword.Text)
                    {
                        this.ShowWarning("两次密码输入不一致");
                        return;
                    }
                    if (cb_Auth.SelectedItem == null)
                    {

                        this.ShowWarning("请选择用户角色");
                        return;
                    }


                    var res = await this._userManager.UpdateUserAsync(new UserUpdataDto
                    {
                        Id = Convert.ToInt32(selectedRow.Cells[0].Value),
                        UserName = txt_UserName.Text,
                        UserPassword = txt_Password.Text,
                        RoleId = (cb_Auth.SelectedItem as RoleInfoModel).Id,
                    });
                    if (res.Code == SystemEnums.ResCode.Success)
                    {
                        this.ShowOk("删除成功！");
                        this.GetAllUser();
                    }
                    else
                    {
                        this.ShowError(res.Msg);
                    }

                }
            };
        }
    }
}
